#include <yaml-cpp/yaml.h>
#include <iostream>
#include <vector>
#include "CMC.h"
#include "MC.h"
#include "SMC.h"
#include "SC.h"
#include "Single.h"

using std::vector;
using std::cerr;
using std::endl;
using YAML::Node;
using YAML::LoadFile;

int main(int argc, char *argv[]){
  const Node &exp = LoadFile("../skt/config/exp.yaml");
  string cfile = "../skt/config/yaml/";
  if(argc > 1) cfile += argv[1];
  else cfile += exp["config"].as<string>();
  const Node &c = LoadFile(cfile);

  vector<PN *> pv;
  // add the central management console //
  CMC *cmc = nullptr; MC *mc = nullptr; SMC *smc = nullptr;
  if(c["cmc"]){
    cmc = new CMC(c["cmc"]);
    pv.push_back(cmc);
    cmc->Ln();
  } // end if
  // add the master crate //
  if(c["mc"]){
    if(cmc){
      mc = new MC(c["mc"]);
      mc->Ln();
      *mc >> *cmc;
      pv.push_back(mc);
    } // end if
    else{
      smc = new SMC(c["mc"]);
      smc->Ln();
      pv.push_back(smc);
    } // end else
  } // end if
  // add slave PXI crates //
  if(c["sc"]){
    for(auto &p : c["sc"]){
      SC *sc = new SC(p);
      pv.push_back(sc);
      sc->Ln();
      if(cmc) *sc >> *cmc;
      else if(smc) *sc >> *smc;
      else{
        cerr << "No cmc or smc" << endl;
        exit(1);
      } // end else
    } // end for
  } // end if
  if(c["single"]){ // single console
    if(pv.size()){
      cerr << "Single node mode, but PN list nonempty." << endl;
      exit(1);
    } // end if
    Single *s = new Single(c["single"]);
    pv.push_back(s);
    s->Ln();
  } // end if

  if(pv.size()){
    for(auto &p : pv) p->Generate();
    for(auto &p : pv) delete p;
  } // end if
  else{
    std::cerr << "No physical nodes registered." << std::endl;
    exit(1);
  } // end else

  return 0;
} // end main function
